#include "msgsgexamp.h"
#include <stdlib.h>

int main(int argc, char **argv) {
    int msgid;
    int type;
    struct my_msg_st *my_data = (struct my_msg_st *)malloc(sizeof(struct my_msg_st));

    if (argc < 2) {
        printf("USAGE: msgexample msgtype\n");
        return -1;
    }

    type = atoi(argv[1]);
    if (type < 1 || type > 3) {  // 修正类型判断范围
        printf("msgtype should be one of 1, 2, 3\n");
        return -1;
    }

    msgid = msgget((key_t)MSG_KEY, IPC_CREAT | S_IRUSR | S_IWUSR);
    if (msgid == -1) {
        perror("get message queue failed ");
        return -1;
    }

    while (1) {
        // 修正 msgrcv 的接收长度为消息内容长度
        if (msgrcv(msgid, (void *)my_data, sizeof(my_data->text), (long)type, IPC_NOWAIT) != -1) { 
            printf("The message type is: %ld\n", my_data->my_msg_type);
            printf("The message content is: %s\n", my_data->text);
        } else if (ENOMSG == errno) {
            printf("there is no message matched to message type\n");
            break;
        }
    }

    free(my_data);  // 释放动态分配的内存
    return 0;
}
